﻿using Flurl.Http;
using MySqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using worldcup.Models;
using worldcup.Models.Entity;

namespace worldcup.DataAccess
{
    /// <summary>
    /// 前端接口服务
    /// </summary>
    public class DataService : BaseService
    {
        #region 查询

        //查询积分排行榜
        public PostResult<List<RankResponse>> RankList()
        {
            var dt = db.SqlQuery<RankResponse>(@"select  headimg,REPLACE(mobile, SUBSTR(mobile,4,4), '****') as 'mobile' ,score from   t_users order by score DESC LIMIT 100");
            return new PostResult<List<RankResponse>>
            {
                data = dt,
                ret = 0,
            };
        }

        //查询竟猜记录
        public PostResult<List<JingcaiResonse>> JingcaiResult(string token, string status)
        {
            var user = db.Queryable<t_users>().Where(c => c.token == token).First();
            var type = "N";
            if (status == "1")
            {
                type = "Y";
            }
            var dt = db.SqlQuery<JingcaiResonse>(string.Format(@"select b.winner, a.winnerid,a.winnername,b.countryAname,c.flag as 'countryAFlag',b.countryBname,d.flag as 'countryBFlag',b.`group`,b.gamedate 
                        from t_jingcai a
                        JOIN t_games b on a.gameid=b.id
                        JOIN t_country c on b.countryAId=c.id
                        JOIN t_country d on b.countryBId=d.id
                        where b.status='{0}' and a.userid={1}", type, user.id));

            return new PostResult<List<JingcaiResonse>>
            {
                data = dt,
                ret = 0,
            };
        }

        //查询最新赛事
        public PostResult<List<NextGames>> NextGames()
        {
            var dt = db.SqlQuery<NextGames>(@"select a.*,b.flag as 'countryAFlag',c.flag as 'countryBFlag' from (
                                SELECT * 
                                 from t_games 
                                  where DATE(gamedate)=(
                                                    select DATE(gamedate) from t_games where status='N' order by gamedate
                                                    LIMIT 1
                                                    )
                                )
                                a JOIN t_country b
                                 on a.countryAId=b.id
                                JOIN t_country c
                                 on a.countryBId=c.id");

            return new PostResult<List<NextGames>>
            {
                data = dt,
                ret = 0
            };
        }

        #endregion

        #region 执行
        //登录，验证码
        public PostResult<string> Login(Login request)
        {
            var param = request;

            var account = db.Queryable<t_users>().Where(c => c.mobile == param.mobile).ToList();


            var verifcode = db.Queryable<t_verifcode>().Where(c => c.mobile == param.mobile).ToList().OrderByDescending(c => c.createtime);

            if (!verifcode.Any())
            {
                return new PostResult<string>()
                {
                    ret = 1,
                    msg = "验证码错误，请重新输入",
                    data = null
                };
            }
            else if (!verifcode.First().verifcode.Equals(param.verifycode) || verifcode.First().expiredate < DateTime.Now)
            {
                return new PostResult<string>()
                {
                    ret = 1,
                    msg = "验证码错误或已过期，请重新输入",
                    data = null
                };
            }
            var token = Guid.NewGuid().ToString().Replace("-", "");
            if (account.Any())
            {
                var obj = account.First();
                obj.token = token;
                var ct = db.Update(obj);
            }
            else
            {
                db.Insert<t_users>(new t_users
                {
                    mobile = param.mobile,
                    token = token,
                    headimg = "",
                    score = 0,
                    ranking = 0,
                    creatat = DateTime.Now
                });
            }

            return new PostResult<string>()
            {
                ret = 0,
                msg = "登录成功",
                data = token
            };
        }

        public PostResult<string> SendMsg(SendMsg request)
        {
            if (string.IsNullOrEmpty(request.mobile))
            {
                return new PostResult<string>()
                {
                    ret = 1,
                    data = $"请输入手机号",
                };
            }
            var verifycode = GenVerifyCodeNum();
            var msg = $"验证码:{verifycode},您正在登录账号, 10分钟内输入有效。";

            #region 云片发送短信
            var apikey = "7cb9926b9a3328e9df96d59eafea7e30";
            // 智能模板发送短信url
            string url_send_sms = "https://sms.yunpian.com/v2/sms/single_send.json";
            string data_send_sms = "apikey=" + apikey + "&mobile=" + request.mobile + "&text=" + msg;
            try
            {
                //var responseString = await "https://sms.yunpian.com/v2/sms/single_send.json"
                //       .PostUrlEncodedAsync(new { apikey = apikey, mobile = request.mobile, text = msg })
                //       .ReceiveString();
            }
            catch (Exception e)
            {
            }
            #endregion

            //调用发送短信sdk
            db.Insert(new t_verifcode
            {
                mobile = request.mobile,
                verifcode = verifycode.ToString(),
                expiredate = DateTime.Now.AddMinutes(10),
                createtime = DateTime.Now,
                msg = msg
            });
            return new PostResult<string>()
            {
                ret = 0,
                data = $"验证码发送成功",
            };
        }

        //签到
        public PostResult<string> Sign(string token)
        {
            var user = db.Queryable<t_users>().Where(c => c.token == token).First();
            var records = db.Queryable<t_signup>().Where(c => c.mobile == user.mobile).ToList();
            if (!records.Any() || !records.Any(c => Convert.ToDateTime(c.createAt).ToString("yyyy-MM-dd").Equals(DateTime.Now.ToString("yyyy-MM-dd"))))
            {
                db.Insert<t_signup>(new t_signup { createAt = DateTime.Now, ip = "", mobile = user.mobile });

                user.score = (user.score ?? 0) + 2;
                db.Update(user);

                db.Insert<t_integrals>(new t_integrals { score = 2, content = "签到成功,增加2积分", createAt = DateTime.Now });
                return new PostResult<string>()
                {
                    ret = 0,
                    data = $"签到成功,增加2积分",
                };
            }
            else
            {
                return new PostResult<string>()
                {
                    ret = 1,
                    data = $"今日已经签到",
                };
            }
        }

        //提交竞猜
        public PostResult<string> Submit(Submit info)
        {
            var param = info;
            var user = db.Queryable<t_users>().Where(c => c.token == param.token).First();

            var game = db.Queryable<t_games>().Where(c => c.id == param.id).First();

            var guessWinerid = 0;
            var guessWinerName = "平局";
            if (param.winnertype == 1)
            {
                guessWinerid = game.countryAId ?? 0;
                guessWinerName = game.countryAname;
            }

            if (param.winnertype == 3)
            {
                guessWinerid = game.countryBId ?? 0;
                guessWinerName = game.countryBname;
            }

            var guess = db.Queryable<t_jingcai>().Where(c => c.gameid == param.id && c.userid == user.id).ToList();
            if (guess.Any())
            {
                if (game.gamedate < DateTime.Now.AddHours(1))
                {
                    return new PostResult<string> { ret = 1, data = "临近开赛1小时内，不能修改" };
                }

                //比赛开始前还可以改
                var one = guess.First();
                one.winnerid = guessWinerid;
                one.winnerName = guessWinerName;
                db.Update<t_jingcai>(one);
            }
            else
            {
                db.Insert<t_jingcai>(new t_jingcai
                {
                    gameid = param.id,
                    winnerid = guessWinerid,
                    winnerName = guessWinerName,
                    createAt = DateTime.Now,
                    userid = user.id
                });
            }

            return new PostResult<string> { };
        }

        #endregion

        #region Helper
        /// <summary>
        /// 生成4位数字验证码字符串
        /// </summary>
        /// <returns></returns>
        public static string GenVerifyCodeNum()
        {
            string chkCode = string.Empty;
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }

            return chkCode;
        }
        #endregion
    }
}